import React, { useCallback, useMemo, useEffect, useState, useRef } from "react";
import Taro from "@tarojs/taro";
import { observer } from "mobx-react";
import i18n from "i18n-js";
import { GStyleSheet } from "@/utils/DarkMode";
import BottomAlert from "@/components/Alert/BottomAlert";
import { View, Text, Image, Input, PickerView, PickerViewColumn } from "@tarojs/components";

import PageContainer from "@/components/PageContainer";
import deviceListModel from "@/models/deviceList";
import { getItemForPk } from "@/config/product";
import ListItem from "@/components/ListItem";
import Switch from "@/components/Switch";
import { fetchDeviceAlarmSetting, updateDeviceAlarmSetting } from "@/services/deviceAlarm";
import alarmPush, { ISettingEditParam, IWxNotDisturbTime, getDisturbTimeText } from "@/models/alarmPush";
import { useAlarmPushStore } from "@/hooks";
import { filterDeviceCanShare } from "../share/shareList/models";

const hourOptions: number[] = [];
for (let i = 0; i < 24; i++) {
  hourOptions.push(i);
}

const dstyle = GStyleSheet.create({
  scroll: {

  },
  pickerView: {
    height: 200,
  },
  noneTips: {
    textAlign: 'center',
    padding: '50PX 20PX',
    width: '100%',
    display: 'block',
    boxSizing: 'border-box',
    color: '#999999',
    fontSize: 14,
  },
  pickerViewItem: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  },
  unitView: {
    position: 'absolute',
    width: '100%',
    height: 200,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    top: 0,
    zIndex: -1,
  },
  titleTips: {
    fontSize: 14,
    color: '#999999',
    padding: '0PX 0PX 10PX 10PX',
    display: 'block'
  },
  unitViewItem: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
    position: 'relative',
    left: 40,
    fontSize: 16,
    color: '#999'
  },
  unitCenter: {
    position: 'absolute',
    left: '50%',
    top: '50%',
    marginTop: '-11PX',
    marginLeft: 10
  },
  icon: {
    width: 24,
    height: 24,
  },
  tips: {
    fontSize: 14,
    color: '#999999',
    display: 'block',
    padding: '6PX 20PX'
  },
});

const DeviceNoti: React.FC = () => {
  const [editTime, setEditTime] = useState<IWxNotDisturbTime | undefined>(undefined);
  const {  wxDoNotDisturbTime, wxDoNotDisturb
  } = useAlarmPushStore();

  const styles = dstyle.style
  const [alarmState, setAlarmState] = useState({})
  const cacheRef = useRef({})

  const devices = deviceListModel.data.filter(item => {
    const productConfig = getItemForPk(item.productKey)
    if (productConfig && productConfig.supportDeviceAlarm && filterDeviceCanShare(item)) {
      return true
    }
  })

  useEffect(() => {
    devices.map(async (item) => {
      const data = await fetchDeviceAlarmSetting(item.mac, item.productKey)
      if (data.success) {
        setAlarmState((oValue) => {
          oValue[item.deviceId] = data.data?.wxDoNotDisturb
          return {...oValue}
        })

        cacheRef.current[item.deviceId] = data.data;
      }
    })
  }, [])

  const changeDeviceNotiConfig = async (id, val) => {
    const currentData = cacheRef.current[id]
    currentData['wxDoNotDisturb'] = val
    const data = await updateDeviceAlarmSetting(currentData)
    if (!data.success) {
      // 异常处理
    }
    setAlarmState((oValue) => {
      oValue[id] = val
      return {...oValue}
    })
  }

  const wechatChange = useCallback(async (p: ISettingEditParam) => {
    // 编辑打开微信通知
    const res = await alarmPush.editWechatSetting(p);
  }, [])


  const showTimeEdit = useCallback(() => {
    setEditTime(wxDoNotDisturbTime || { wxBeginHour: 0, wxBeginMinute: 0, wxEndHour: 0, wxEndMinute: 0 });
  }, [wxDoNotDisturbTime]);

  const onCancel = useCallback(() => {
    setEditTime(undefined);
  }, [])

  const onConfirm = useCallback(() => {
    console.log('editTime', editTime);
    wechatChange(editTime as IWxNotDisturbTime);
    onCancel();
  }, [onCancel, editTime, wechatChange]);

  const onChange = useCallback((e) => {
    const val = e.detail.value as number[];
    setEditTime({ ...editTime as IWxNotDisturbTime, wxBeginHour: val[0], wxEndHour: val[1] });
  }, [editTime])

  return (
    <PageContainer title={i18n.t('免打扰设置')} >
      <ListItem extra={
        <Switch checked={wxDoNotDisturb} onChange={(e) => { 
          wechatChange({wxDoNotDisturb: !wxDoNotDisturb})
         }}
        />
      }
      >
        {i18n.t('免打扰开关')}
      </ListItem>
      <ListItem 
        onPress={showTimeEdit}
        extra={<Text>{getDisturbTimeText(wxDoNotDisturbTime)}</Text>}
      >
        {i18n.t('DO_NOT_DIATURB_PERIOD')}
      </ListItem>

      <Text style={styles.tips}>{i18n.t('生效设备')}</Text>
      {
        devices.map((item, index) => {
          const productConfig = getItemForPk(item.productKey)
          console.log('alarmState[item.deviceId]', item.deviceId, JSON.stringify(alarmState))
          return (
            <ListItem 
              extra={
                <Switch checked={alarmState[`${item.deviceId}`]} onChange={(e) => {
                  changeDeviceNotiConfig(item.deviceId, e)
                 }}
                />
              }
              key={item.deviceId} 
              icon={<Image src={productConfig.icon} style={styles.icon}></Image>}
            >
              {item.name}
            </ListItem>
          )
        })
      }

      {
        devices.length === 0 && (
          <Text style={styles.noneTips}>{i18n.t('暂无数据')}</Text>
        )
      }
      
      <BottomAlert
        isOpened={!!editTime}
        onCancel={onCancel}
        onConfirm={onConfirm}
      >
        <PickerView style={styles.pickerView} value={[editTime?.wxBeginHour, editTime?.wxEndHour]} onChange={onChange}>
          <PickerViewColumn>
            {hourOptions.map(item => {
              return (
                <View key={item} style={styles.pickerViewItem}>
                  <Text>{item}</Text>
                </View>
              );
            })}
          </PickerViewColumn>
          <PickerViewColumn>
            {hourOptions.map(item => {
              return (
                <View key={item} style={styles.pickerViewItem}>
                  <Text>{item}</Text>
                </View>
              );
            })}
          </PickerViewColumn>
        </PickerView>
        <View style={styles.unitView}>
          <View style={styles.unitViewItem}>
            <Text>时</Text>
          </View>
          <View style={styles.unitCenter}>
            <Text>至</Text>
          </View>
          <View style={styles.unitViewItem}>
            <Text>时</Text>
          </View>
        </View>
      </BottomAlert>
    </PageContainer >
  );
}

export default observer(DeviceNoti);
